/*
*Copyright 2021-2023 NERCIS
*
*Licensed under the Apache License, Version 2.0 (the "License");
*you may not use this file except in compliance with the License.
*You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*Unless required by applicable law or agreed to in writing, software
*distributed under the License is distributed on an "AS IS" BASIS,
*WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*See the License for the specific language governing permissions and
*limitations under the License.
*/

package cn.ac.nercis.pes.repository.mapper.manage;

import cn.ac.nercis.pes.model.dto.manage.UserDTO;
import cn.ac.nercis.pes.model.dto.manage.UserDetailDTO;
import cn.ac.nercis.pes.repository.constant.BaseConstants;
import cn.ac.nercis.pes.repository.model.manage.RoleDO;
import cn.ac.nercis.pes.repository.model.manage.UserDO;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import org.mapstruct.ReportingPolicy;
import org.mapstruct.factory.Mappers;

import java.util.Objects;
import java.util.Optional;

/**
 * 用户类型映射
 *
 * @author zpy
 * @date 2021/3/9
 */
@Mapper(componentModel = "spring",
        imports = {Optional.class,
                Objects.class,
                RoleDO.class,
                BaseConstants.class},
        unmappedTargetPolicy = ReportingPolicy.IGNORE)
public interface UserMapper {
    UserMapper INSTANCE = Mappers.getMapper(UserMapper.class);

    /**
     * 转换为DTO类型用户信息
     * @param entity DO类型用户信息
     * @return 返回DTO类型用户信息
     */
    @Mapping(target = "roleId", expression = "java(Optional.ofNullable(entity).filter(o->Objects.nonNull(o.getRoles())).flatMap(o->o.getRoles().stream().findFirst()).map(RoleDO::getId).orElse(\"\"))")
    @Mapping(target = "roleName", expression = "java(Optional.ofNullable(entity).filter(o->Objects.nonNull(o.getRoles())).flatMap(o->o.getRoles().stream().findFirst()).map(RoleDO::getDescription).orElse(\"\"))")
    @Mapping(target = "type", expression = "java(Optional.ofNullable(entity.getWebServer()).filter(r->r).map(r->BaseConstants.SERVER_USER_TYPE).orElse(BaseConstants.INTERNAL_USER_TYPE))")
    UserDTO toDTO(UserDO entity);

    UserDO toDO(UserDetailDTO dto);
}